﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.LinqBuilder;
using Microsoft.EntityFrameworkCore;
using Queer.Entity;
using Queer.IService.SystemManage;
using Queer.Model.Param.SystemManage;
using Queer.Model.Result.SystemManage;
using Queer.Util;
using Queer.Util.Helper;
using Queer.Util.Model;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Queer.Service.SystemManage
{
    /// <summary>
    /// 创 建：song
    /// 日 期：2020-12-19 08:59
    /// 描 述：数据字典值服务类
    /// </summary>

    public class DataDictDetailService : IDataDictDetailService, ITransient
    {
        private readonly IRepository<DataDictDetailEntity> _dataDictDetailDB;

        public DataDictDetailService(IRepository<DataDictDetailEntity> dataDictDetailDB)
        {
            _dataDictDetailDB = dataDictDetailDB;
        }

        #region 获取数据

        /// <summary>
        /// 带条件查询所有
        /// </summary>
        public async Task<List<DataDictDetailEntity>> GetList(DataDictDetailListParam param)
        {
            var query = ListFilter(param);

            var data = await query.ToListAsync();
            return data;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        public async Task<List<DataDictDetailEntity>> GetPageList(DataDictDetailListParam param, Pagination pagination)
        {
            var query = ListFilter(param);

            var data = await query.OrderByDescending(a => a.Id).ToPagedListAsync(pagination.PageIndex, pagination.PageSize);


            // 分页参数赋值
            pagination.TotalCount = data.TotalCount;
            return data.Items.ToList();
        }

        /// <summary>
        /// 根据ID获取对象
        /// </summary>
        public async Task<DataDictDetailEntity> GetEntity(long id)
        {
            var list = await _dataDictDetailDB.AsQueryable(p => p.Id == id).ToListAsync();
            return list.FirstOrDefault();
        }

        public async Task<int> GetMaxSort()
        {
            object result = await "SELECT MAX(positionSort) FROM DataDictDetailEntity".SqlNonQueryAsync();
            int sort = result.ParseToInt();
            sort++;
            return sort;
        }

        /// <summary>
        /// 查询多个ID主键数据
        /// </summary>
        public async Task<List<DataDictDetailEntity>> GetListByIds(string ids)
        {
            if (ids.IsNullOrEmpty())
                throw new BusinessException("参数不合法！");

            var idArr = TextHelper.SplitToArray<long>(ids, ',').ToList();
            var data = await _dataDictDetailDB.AsQueryable(a => idArr.Contains(a.Id.GetValueOrDefault())).ToListAsync();

            return data;
        }

        /// <summary>
        /// 根据条件查询获取select控件所需内容
        /// </summary>
        public List<DataDictDetailSelect> GetListJsonForSelect(DataDictDetailListParam param)
        {
            List<DataDictDetailSelect> RtnData = new List<DataDictDetailSelect>();
            var query = ListFilter(param);
            query = query.Where(p => p.DictStatus == 1);
            if (!string.IsNullOrEmpty(param.DictTypes))
            {
                var idArr = TextHelper.SplitToArray<string>(param.DictTypes, ',').ToList();
                foreach (var item in idArr)
                {
                    DataDictDetailSelect itemD = new DataDictDetailSelect();
                    itemD.DictType = item;
                    var itemDetail = query.Where(p => p.DictType == item);
                    itemD.data = itemDetail.ToList();
                    RtnData.Add(itemD);
                }
            }
            else
            {
                DataDictDetailSelect itemD = new DataDictDetailSelect();
                itemD.DictType = param.DictType;
                itemD.data = query.ToList();
                RtnData.Add(itemD);
            }
            return RtnData;
        }

        #endregion

        #region 提交数据

        public async Task SaveForm(DataDictDetailEntity entity)
        {
            if (entity.Id.IsNullOrZero())
            {
                await _dataDictDetailDB.InsertNowAsync(entity);
            }
            else
            {
                await _dataDictDetailDB.UpdateNowAsync(entity, ignoreNullValues: true);
            }
        }

        public async Task DeleteForm(string ids)
        {
            if (string.IsNullOrWhiteSpace(ids))
                throw new BusinessException("参数不合法！");

            var _ids = ids.Split(",");

            await _dataDictDetailDB.BatchFakeDeleteAsync(_ids);
        }

        #endregion

        #region 私有方法

        private IQueryable<DataDictDetailEntity> ListFilter(DataDictDetailListParam param)
        {
            IQueryable<DataDictDetailEntity> query = _dataDictDetailDB.AsQueryable(false);

            if (!string.IsNullOrEmpty(param.DictType))
                query = query.Where(p => p.DictType.Contains(param.DictType));

            if (!string.IsNullOrEmpty(param.DictTypes))
            {
                var idArr = TextHelper.SplitToArray<string>(param.DictTypes, ',').ToList();
                query = query.Where(p => idArr.Contains(p.DictType));
            }

            if (!string.IsNullOrEmpty(param.DictValue))
                query = query.Where(p => p.DictValue.Contains(param.DictValue));

            if (param.DictStatus.HasValue)
                query = query.Where(p => p.DictStatus == param.DictStatus);

            if (param.DictKey.HasValue)
                query = query.Where(p => p.DictKey == param.DictKey);

            query = query.Where(a => a.IsDelete != true);

            return query;
        }

        #endregion
    }
}